/**
 * @file name TBPersonEditActivity.java
 */
package com.digital.community;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.digital.community.common.utils.HttpUtils;
import com.digital.community.common.utils.StringUtils;
import com.digital.community.common.utils.ToastUtils;

/**
 * 
 * @author yarine.gao
 * @date 2012-11-13
 * @version 1.0.0
 */
public class TBPersonEditActivity extends Activity {

	private String guid = null;
	
	private EditText nameET;
	private Spinner genderSpinner;
	private Spinner nationSpinner;
	private Spinner cardTypeSpinner;
	private EditText cardnoET;
	
	private ArrayList<String> nationList;
	private ArrayList<String> cardtypeList;
	private ArrayList<String> genderList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tbperson_update);
		
		Intent intent = getIntent();
		guid = intent.getStringExtra("guid");
        nationList = intent.getStringArrayListExtra("nation");
        cardtypeList = intent.getStringArrayListExtra("cardtype");
        genderList = intent.getStringArrayListExtra("gender");
		
		
		nameET = (EditText)findViewById(R.id.et_name);
		genderSpinner = (Spinner)findViewById(R.id.sp_gender);
		nationSpinner = (Spinner)findViewById(R.id.sp_nation);
		cardTypeSpinner = (Spinner)findViewById(R.id.sp_cardtype);
		cardnoET = (EditText)findViewById(R.id.et_cardno);
		
		
		toLoadData();
	}
	
	private String name;
	private String gender;
	private String nation;
	private String cardtype;
	private String cardno;
    ProgressDialog proDialog;
	private void toLoadData() {
		proDialog = ProgressDialog.show(TBPersonEditActivity.this, "请等待", "正在请求数据...",true,true);
		new Thread() {
			public void run() {
				HashMap<String, String> params = new HashMap<String, String>();
    	    	params.put("guid", guid);
    	    	
    	    	Bundle bundle = HttpUtils.getPost("toQueryById.do", params, 3000, TBPersonEditActivity.this);
    	    	if(bundle.getInt("code") == HttpUtils.SUCCESS) {
    	    		String content = bundle.getString("content");
    	    		if(StringUtils.isBlank(content) || "[]".equals(content)) {
    	    			handler.sendEmptyMessage(HANDLER_CONN_ERROR);
    	    			return;
    	    		} else {
    	    			try {
    	    				JSONObject json = new JSONObject(content);
    	    				name = json.getString("name");
    	    				gender = json.getString("gender");
    	    				nation = json.getString("nation");
    	    				cardtype = json.getString("cardtype");
    	    				cardno = json.getString("cardno");
    	    				
    	    				handler.sendEmptyMessage(HANDLER_CONN_SUCCESS);
    	    			} catch (Exception e) {
    	    				System.out.println(e);
    	    				handler.sendEmptyMessage(HANDLER_CONN_ERROR);
						}
    	    		}
    	    	} else {
    	    		handler.sendEmptyMessage(HANDLER_CONN_ERROR);
    	    	}
			};
		}.start();
	}
	
	private static final int HANDLER_CONN_ERROR = 100;
	private static final int HANDLER_CONN_SUCCESS = 101;
	private static final int HANDLER_UPDATE_SUCCESS = 102;
	private static final int HANDLER_UPDATE_ERROR = 103;
    Handler handler = new Handler() {
    	
    	public void handleMessage(android.os.Message msg) {
    		if(proDialog != null && proDialog.isShowing()) {
				proDialog.dismiss();
			}
    		
    		switch (msg.what) {
			case HANDLER_CONN_ERROR:
				showDialog(DIALOG_NETWORK_ERROR);
				break;
			case HANDLER_CONN_SUCCESS:
				nameET.setText(name);
				cardnoET.setText(cardno);
				
		    	ArrayAdapter genderSpinnerAdapter = new ArrayAdapter<String>(TBPersonEditActivity.this, android.R.layout.simple_spinner_item, genderList);
		    	genderSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    	genderSpinner.setAdapter(genderSpinnerAdapter);
		    	int pos = 0;
		    	if(genderList != null && genderList.size() > 0 && StringUtils.isNotBlank(gender)) {
		    		for(int i = 0; i < genderList.size(); i ++) {
		    			if(gender.equals(genderList.get(i))) {
		    				pos = i;
		    				break;
		    			}
		    		}
		    	}
		    	genderSpinner.setSelection(pos);
		    	
		    	pos = 0;
		    	ArrayAdapter nationSpinnerAdapter = new ArrayAdapter<String>(TBPersonEditActivity.this, android.R.layout.simple_spinner_item, nationList);
		    	nationSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    	nationSpinner.setAdapter(nationSpinnerAdapter);
		    	if(nationList != null && nationList.size() > 0 && StringUtils.isNotBlank(nation)) {
		    		for(int i = 0; i < nationList.size(); i ++) {
		    			if(nation.equals(nationList.get(i))) {
		    				pos = i;
		    				break;
		    			}
		    		}
		    	}
		    	nationSpinner.setSelection(pos);
		    	
		    	pos = 0;
		    	ArrayAdapter cardTypeSpinnerAdapter = new ArrayAdapter<String>(TBPersonEditActivity.this, android.R.layout.simple_spinner_item, cardtypeList);
		    	cardTypeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		    	cardTypeSpinner.setAdapter(cardTypeSpinnerAdapter);
		    	if(cardtypeList != null && cardtypeList.size() > 0 && StringUtils.isNotBlank(cardtype)) {
		    		for(int i = 0; i < cardtypeList.size(); i ++) {
		    			if(cardtype.equals(cardtypeList.get(i))) {
		    				pos = i;
		    				break;
		    			}
		    		}
		    	}
		    	
				break;
			case HANDLER_UPDATE_SUCCESS:
				ToastUtils.showTrueToast(TBPersonEditActivity.this, getLayoutInflater(), "更新成功!", false);
				break;
			case HANDLER_UPDATE_ERROR:
				showDialog(DIALOG_UPDATE_ERROR);
				break;
    		}
    	}
    };
    
    private static final int DIALOG_NETWORK_ERROR = 200;
    private static final int DIALOG_ADD_ERROR = 201;
    private static final int DIALOG_QUERY_NETWORK_ERROR = 202;
    private static final int DIALOG_DEL_CONN_ERROR = 203;
    private static final int DIALOG_UPDATE_ERROR = 204;
    @Override
	protected Dialog onCreateDialog(int id) {
		if(!isActive) return null;
		switch (id) {
		case DIALOG_NETWORK_ERROR:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,网络联接失败!")
			.setPositiveButton("重试", new Retry())
			.setNegativeButton("取消", new Cancle()).create();
		case DIALOG_UPDATE_ERROR:
			return new AlertDialog.Builder(this).setTitle("提示信息").setMessage("对不起,更新失败!")
			.setPositiveButton("重试", new RetryUpdate())
			.setNegativeButton("取消", new Cancle()).create();
		default: 
			return null;
		}
    }
    
    private class Retry implements OnClickListener {
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
    		toLoadData();
    	}
    }
    private class RetryUpdate implements OnClickListener {
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
    		updatePerson();
    	}
    }
    
    private class Cancle implements OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
		}
    }
    
    private boolean isActive = true;
    @Override
    protected void onDestroy() {
    	isActive = false;
    	super.onDestroy();
    }
    
    public void toUpdatePerson(View view) {
    	name = nameET.getText().toString();
    	gender = genderSpinner.getSelectedItem().toString();
    	nation = nationSpinner.getSelectedItem().toString();
    	cardtype = cardTypeSpinner.getSelectedItem().toString();
    	cardno = cardnoET.getText().toString();
    	
    	if(StringUtils.isBlank(name)) {
    		ToastUtils.showErrorToast(this, getLayoutInflater(), "姓名不能为空!", false);
    		return;
    	}
    	if(StringUtils.isBlank(gender)) {
    		ToastUtils.showErrorToast(this, getLayoutInflater(), "性别不能为空!", false);
    		return;
    	}
    	if(StringUtils.isBlank(nation)) {
    		ToastUtils.showErrorToast(this, getLayoutInflater(), "民族不能为空!", false);
    		return;
    	}
    	if(StringUtils.isBlank(cardno)) {
    		ToastUtils.showErrorToast(this, getLayoutInflater(), "证件号不能为空!", false);
    		return;
    	}
    	
    	updatePerson();
    }
    
    private void updatePerson() {
    	proDialog = ProgressDialog.show(TBPersonEditActivity.this, "请等待", "正在请求数据...",true,true);
    	new Thread() {
    		public void run() {
    			HashMap<String, String> params = new HashMap<String, String>();
    	    	params.put("name", name);
    	    	params.put("gender", gender);
    	    	params.put("nation", nation);
    	    	params.put("cardType", cardtype);
    	    	params.put("cardNo", cardno);
    	    	params.put("guid", guid);
    	    	
    	    	Bundle bundle = HttpUtils.getPost("toUpdate.do", params, 3000, TBPersonEditActivity.this);
    	    	if(bundle.getInt("code") == HttpUtils.SUCCESS) {
    	    		String content = bundle.getString("content");
    	    		if(StringUtils.isBlank(content) || "[]".equals(content)) {
    	    			handler.sendEmptyMessage(HANDLER_CONN_ERROR);
    	    			return;
    	    		} else {
    	    			try {
    	    				JSONObject json = new JSONObject(content);
    	    				int success = json.getInt("success");
    	    				if(success == 1) {
    	    					handler.sendEmptyMessage(HANDLER_UPDATE_SUCCESS);
    	    					return;
    	    				} else {
    	    					handler.sendEmptyMessage(HANDLER_UPDATE_ERROR);
    	    					return;
    	    				}
    	    			} catch (Exception e) {
    	    				System.out.println(e);
    	    				handler.sendEmptyMessage(HANDLER_UPDATE_ERROR);
						}
    	    		}
    	    	} else {
    	    		handler.sendEmptyMessage(HANDLER_UPDATE_ERROR);
    	    	}
    		};
    	}.start();
    }
}
